<template>
  <view class="container">
    <view class="header">{{ info.planName }}</view>

    <!-- 添加上课时间显示 -->

    <div style="padding: 30rpx; background: #fff; border-radius: 20rpx">
      <div v-for="(node, nodeIndex) in dataList" :key="nodeIndex">
        <view class="f ac xb mt20r">
          <view
            class="title f ac rds20r"
            style="
              background-color: #ededed;
              color: #000;
              padding: 0 10rpx;
              height: 70rpx;
            "
            @click="changePurpose(nodeIndex)"
          >
            <u-icon name="edit-pen"></u-icon>
            <div style="margin-left: 10rpx">{{ node.purpose }}</div>
          </view>
          <view
            class="add"
            style="
              height: 70rpx;
              display: flex;
              align-items: center;
              justify-content: center;
            "
            @click="
              () => {
                currentNode = nodeIndex;
                show2 = true;
              }
            "
          >
            添加动作
          </view>
          <view
            class="delete"
            style="
              height: 70rpx;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-left: 10rpx;
            "
            @click="deleteNode(nodeIndex)"
          >
            <image
              style="width: 40rpx; height: 40rpx"
              src="../../static/del.png"
            ></image>
          </view>
        </view>

        <div v-if="node.exercises && node.exercises.length > 0">
          <view
            v-for="(exercise, eIndex) in node.exercises"
            :key="eIndex"
            class="f ac xb mt30r plan chooseitem mt20r"
            @click="edit(exercise, eIndex, nodeIndex)"
          >
            <view class="f ac" style="flex: 1; justify-content: center">
              <text
                v-if="!exercise.isEditing"
                @click.stop="startEdit(nodeIndex, eIndex)"
              >
                {{ exercise.name }}
              </text>
              <input
                v-else
                v-model="exercise.name"
                class="name-input"
                @blur="finishEdit(nodeIndex, eIndex)"
                @click.stop
                ref="nameInput"
              />
            </view>
            <view class="f ac" style="flex: 1; justify-content: center">
              <div>{{ exercise.sets }} 组 X</div>
              <div style="padding-right: 20rpx">
                {{ exercise.reps.count }}{{ getUnitLabel(exercise.reps.unit) }}
              </div>
            </view>
            <view class="f ac" style="flex: 1; justify-content: center">
              <div>{{ exercise.weighs }}</div>
            </view>
          </view>
        </div>
        <div v-else class="f ac xc mt30r plan chooseitem mt20r">暂无动作</div>
      </div>
    </div>
    <view class="class-time" v-if="isClassStarted">
      上课时间:
      <text class="time-text">{{ formatTime(elapsedTime) }}</text>
    </view>
    <view class="action-buttons">
      <view
        class="button-card start"
        @click="startClass"
        v-if="!isClassStarted"
      >
        <text>开始上课</text>
      </view>

      <view class="button-card timer" @click="goUrl">
        <text>使用计时器</text>
      </view>

      <view class="button-card end" @click="handleEndClass">
        <text>{{ isQianzi ? "客户签字" : "结束课程" }}</text>
      </view>

      <view class="button-card save" @click="saveTemplate">
        <text>保存修改</text>
      </view>
    </view>

    <!-- 添加动作弹窗 -->
    <u-popup :show="show2" @close="resetForm" round>
      <view class="popup-content">
        <view class="form-item">
          <text class="label">动作名称：</text>
          <input
            v-model="form.name"
            placeholder="请输入动作名称"
            class="input-field"
          />
        </view>

        <view class="form-item">
          <text class="label">组数：</text>
          <input
            type="number"
            v-model="form.sets"
            placeholder="请输入组数"
            class="input-field-small"
          />
          <text class="unit-text">组</text>
        </view>

        <view class="form-item">
          <text class="label">次数：</text>
          <input
            type="number"
            v-model="form.reps.count"
            placeholder="请输入次数"
            class="input-field-small"
          />
          <picker
            mode="selector"
            :range="unitOptions"
            range-key="label"
            :value="unitIndex"
            @change="handleUnitChange"
            class="unit-picker"
          >
            <view class="picker-text">
              {{ unitOptions[unitIndex].label }}
              <u-icon name="arrow-down" size="24"></u-icon>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">重量：</text>
          <input
            v-model="form.weighs"
            placeholder="请输入重量"
            class="input-field"
          />
        </view>

        <view class="button-group">
          <button class="reset-btn" @click="resetForm">重置</button>
          <button class="confirm-btn" @click="adddz">确定</button>
        </view>
      </view>
    </u-popup>

    <!-- 修改目的弹窗 -->
    <u-popup :show="show" @close="show = false">
      <view style="padding: 30rpx">
        <view
          v-for="(item, index) in mdList"
          :key="index"
          class="chooseitem mb20r f ac xb"
          @click="selId = item.id"
        >
          <view v-if="!item.slot" class="bodyr f ac">
            {{ item.title }}
          </view>
          <view v-else>
            <div class="f ac">
              自定义：
              <input v-model="answer" type="text" />
            </div>
          </view>
          <image
            v-if="selId == item.id"
            class="sinchoose-on"
            mode=""
            src="/static/xz.png"
            style="width: 30rpx; height: 30rpx"
          ></image>
          <view v-else class="sinchoose"></view>
        </view>
        <view class="tc btn" @click="submit">确定</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  planDetails,
  stop,
  start,
  iz_sign,
  updataPlanIns,
  getCount,
  editCount,
} from "../../api/fit";
export default {
  data() {
    return {
      isQianzi: false,
      show: false,
      title: "添加动作",
      dataList: [],
      planName: "",
      unitOptions: [
        { label: "次", value: "c" },
        { label: "秒", value: "s" },
        { label: "分", value: "m" },
      ],
      isClassStarted: false,
      startTime: 0,
      elapsedTime: 0,
      timer: null,
      info: {},
      show2: false,
      currentNode: 0,
      form: {
        name: "",
        sets: "",
        reps: {
          count: "",
          unit: "c",
        },
        weighs: "",
        interval: 30,
      },
      mdList: [
        { id: 1, title: "热身" },
        { id: 2, title: "正式训练" },
        { id: 3, title: "放松拉伸" },
        { id: 4, title: "一般活动GPP" },
        { id: 5, title: "多次数RP" },
        { id: 6, title: "肌力ME" },
        { id: 7, title: "爆发DE" },
        { id: 8, title: "自定义", slot: true },
      ],
      answer: "",
      selId: 0,
      unitIndex: 0,
      infoCount: {},
    };
  },
  onLoad(options) {
    console.log(options, "options");
    this.customerId = options.customerId;
    this.id = options.id;
    this.getInfo();
    this.getNum();
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    this.checkSignStatus();
  },
  onUnload() {
    clearInterval(this.timer);
  },
  methods: {
    async getNum() {
      const res = await getCount(this.customerId);
      this.infoCount = res.data;
    },
    async checkSignStatus() {
      const res = await iz_sign();
      console.log(res, "res");
      this.isQianzi = res.data === 1;
    },
    async getInfo() {
      const res = await planDetails(this.id);
      this.dataList = res.data.nodes;
      this.planName = res.data.planName;
      this.info = res.data;
    },
    getUnitLabel(unit) {
      const option = this.unitOptions.find((opt) => opt.value === unit);
      return option ? option.label : "";
    },
    async startClass() {
      const res = await start(this.info.id);
      console.log(res, "res");
      this.isClassStarted = true;
      this.startTime = Date.now();
      this.timer = setInterval(() => {
        this.elapsedTime = Date.now() - this.startTime;
      }, 1000);
    },
    handleEndClass() {
      clearInterval(this.timer);
      if (this.isQianzi) {
        uni.navigateTo({
          url: `/pages/kecheng/qianzi?id=${this.info.id}&customerId=${this.customerId}`,
        });
      } else {
        this.endClass();
      }
    },
    async endClass() {
      this.isClassStarted = false;
      this.elapsedTime = 0;
      const res = await stop({
        id: this.info.id,
        izSign: "2",
      });
      console.log(res, "res");
      if (res.code === 200) {
        editCount({
          customerId: this.customerId,
          count: Number(this.infoCount.total) + 1,
        }).then((res) => {});
        uni.showToast({
          title: "课程已结束",
          icon: "success",
          duration: 2000,
          success: () => {
            setTimeout(() => {
              uni.navigateBack();
            }, 2000);
          },
        });
      }
    },
    goUrl() {
      uni.navigateTo({
        url: "/pages/jishi/index",
      });
    },
    confirm() {
      this.show = false;
    },
    editExercise(exercise, eIndex, sectionIndex) {
      // 编辑动作逻辑
      console.log(`编辑动作: ${exercise.name}`);
    },
    formatTime(ms) {
      const seconds = Math.floor(ms / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);

      const formattedHours = hours < 10 ? `0${hours}` : hours;
      const formattedMinutes =
        minutes % 60 < 10 ? `0${minutes % 60}` : minutes % 60;
      const formattedSeconds =
        seconds % 60 < 10 ? `0${seconds % 60}` : seconds % 60;

      return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
    },
    async saveTemplate() {
      try {
        uni.showLoading({
          title: "保存中...",
        });

        if (!this.info.planName) {
          throw new Error("请输入计划名称");
        }

        const templateData = {
          planName: this.info.planName,
          nodes: this.dataList,
          id: this.id,
          customerId: this.customerId,
        };

        const res = await updataPlanIns(templateData);
        if (res.code === 200) {
          uni.showToast({
            title: "保存成功",
            icon: "success",
          });
        } else {
          throw new Error(res.msg || "保存失败");
        }
      } catch (error) {
        console.error("保存失败:", error);
        uni.showToast({
          title: error.message || "保存失败",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },
    startEdit(nodeIndex, eIndex) {
      this.dataList[nodeIndex].exercises[eIndex].isEditing = true;
      this.$nextTick(() => {
        if (this.$refs.nameInput) {
          this.$refs.nameInput.focus();
        }
      });
    },
    finishEdit(nodeIndex, eIndex) {
      this.dataList[nodeIndex].exercises[eIndex].isEditing = false;
    },
    handleUnitChange(e) {
      this.unitIndex = e.detail.value;
      this.form.reps.unit = this.unitOptions[this.unitIndex].value;
    },
    deleteNode(index) {
      uni.showModal({
        title: "确认删除",
        content: "是否确认删除该目的？",
        success: (res) => {
          if (res.confirm) {
            this.dataList.splice(index, 1);
          }
        },
      });
    },
    changePurpose(index) {
      this.currentNode = index;
      this.show = true;
    },
    adddz() {
      if (!this.form.name) {
        uni.showToast({
          title: "请输入动作名称",
          icon: "none",
        });
        return;
      }

      const exercise = {
        name: this.form.name,
        sets: this.form.sets,
        reps: {
          count: this.form.reps.count,
          unit: this.form.reps.unit,
        },
        weighs: this.form.weighs,
        interval: this.form.interval || 30,
      };

      this.dataList[this.currentNode].exercises.push(exercise);
      this.resetForm();
      this.show2 = false;
    },
    resetForm() {
      this.form = {
        name: "",
        sets: "",
        reps: {
          count: "",
          unit: "c",
        },
        weighs: "",
        interval: 30,
      };
      this.show2 = false;
    },
    submit() {
      if (this.selId === 8 && !this.answer) {
        uni.showToast({
          title: "请输入自定义目的",
          icon: "none",
        });
        return;
      }

      const selectedItem = this.mdList.find((item) => item.id === this.selId);
      if (selectedItem) {
        this.dataList[this.currentNode].purpose =
          this.selId === 8 ? this.answer : selectedItem.title;
      }

      this.show = false;
      this.answer = "";
      this.selId = 0;
    },
    edit(exercise, eIndex, nodeIndex) {
      this.currentNode = nodeIndex;
      this.form = {
        name: exercise.name,
        sets: exercise.sets,
        reps: {
          count: exercise.reps.count,
          unit: exercise.reps.unit,
        },
        weighs: exercise.weighs,
        interval: exercise.interval || 30,
      };
      this.unitIndex = this.unitOptions.findIndex(
        (opt) => opt.value === exercise.reps.unit
      );

      // 删除原来的动作
      this.dataList[nodeIndex].exercises.splice(eIndex, 1);
      this.show2 = true;
    },
    deleteExercise(nodeIndex, eIndex) {
      uni.showModal({
        title: "确认删除",
        content: "是否确认删除该动作？",
        success: (res) => {
          if (res.confirm) {
            this.dataList[nodeIndex].exercises.splice(eIndex, 1);
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding: 30rpx;
}

.header {
  font-size: 48rpx;
  font-weight: 900;
  color: #fff;
  background: #000;
  padding: 40rpx 20rpx;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  text-align: center;
}

.section {
  margin-bottom: 30rpx;
}

.section-block {
  margin-bottom: 40rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx 20rpx;
  background: #000;
  border-radius: 20rpx;
}

.card {
  background: #fff;
  padding: 40rpx;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  transform: translateY(0);
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  }
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #000;
  margin-bottom: 10rpx;
}

.card-detail {
  font-size: 28rpx;
  color: #666;
}

.timer {
  font-size: 48rpx;
  font-weight: 600;
  color: #000;
  text-align: center;
  padding: 20rpx 0;
}

.action-buttons {
  margin-top: 40rpx;
}

.button-card {
  background: #fff;
  padding: 40rpx;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  text-align: center;
  font-size: 32rpx;
  font-weight: 600;
  transform: translateY(0);
  transition: all 0.3s ease;

  &.start {
    background: #fff;
    color: #000;
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.4);
    &:active {
      transform: translateY(4rpx);
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
    }
  }

  &.timer {
    background: #000;
    color: #fff;
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.15);

    &:active {
      transform: translateY(4rpx);
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
    }
  }

  &.end {
    background: #fff;
    color: #000;
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.15);

    &:active {
      transform: translateY(4rpx);
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
    }
  }
}
.chooseitem {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border: 1px solid #ebebeb;
  border-radius: 20rpx;
  background-color: #fff;

  &:active {
    background: #f8f8f8;
  }
}

.save {
  background: #000;
  color: #fff;
  margin-top: 20rpx;
}

.title {
  flex: 1;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background-color: #f4f1f4;
  color: #a385a1;
  border-radius: 20rpx;
  height: 70rpx;

  .rds50 {
    margin-right: 12rpx;
  }

  .u-icon {
    margin-left: 12rpx;
  }
}

.add {
  padding: 0 24rpx;
  background: #000;
  color: #fff;
  border-radius: 30rpx;
  font-size: 26rpx;
  display: inline-block;
  transition: all 0.3s ease;
  height: 70rpx;

  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
}

.delete {
  padding: 0 24rpx;
  background: #fff;
  color: #fff;
  border-radius: 30rpx;
  font-size: 26rpx;
  display: inline-block;
  transition: all 0.3s ease;
  height: 70rpx;

  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
}

.name-input {
  width: 100%;
  height: 60rpx;
  padding: 0 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
}

// 通用样式
.mt20r {
  margin-top: 20rpx;
}
.mt30r {
  margin-top: 30rpx;
}
.ml20r {
  margin-left: 20rpx;
}
.f {
  display: flex;
}
.ac {
  align-items: center;
}
.xb {
  justify-content: space-between;
}
.xc {
  justify-content: center;
}
.rds20r {
  border-radius: 20rpx;
}

// 弹窗样式
.popup-content {
  padding: 30rpx;
  width: 600rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.label {
  width: 160rpx;
  font-size: 28rpx;
  color: #333;
  flex-shrink: 0;
}

.input-field {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.input-field-small {
  width: 120rpx;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  text-align: center;
}

.unit-text {
  margin-left: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.unit-picker {
  margin-left: 20rpx;
  width: 140rpx;
}

.picker-text {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.button-group {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  margin-top: 40rpx;
}

.reset-btn,
.confirm-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

.reset-btn {
  background: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: #000;
  color: #fff;
}

.class-time {
  font-size: 36rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.time-text {
  font-weight: bold;
}
</style>
